package com.example.demo.config.login;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.example.demo.datasource.multi.entity.fakeCode;
import com.example.demo.datasource.multi.entity.user;
import com.example.demo.entity.useracount;
import com.example.demo.result.R;
import com.example.demo.result.ResultCode;
import com.example.demo.test.getIpv4IP;
import com.example.demo.util.getip;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Controller
public class logincontroller {

    @ResponseBody
    @CrossOrigin  //目标方法上加入这个解决跨域
    @RequestMapping(value = { "/tokentimeout"})
    public JSONObject tokentimeout(Model model, HttpServletRequest request) {

        System.out.println("sssss");

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",401);
        result5.put("result",null);
        result5.put("message","tokentimeout!");
        result5.put("type","error");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }


    @ResponseBody
    @RequestMapping(value = { "/logout"})
    public JSONObject logout() {
        //获取session
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest().getSession();
        //注销用户，使 session 失效
        session.invalidate();

        Map<String, Object> result5 = new HashMap<String,Object>();
        result5.put("code",0);
        result5.put("result",null);
        result5.put("message","令牌已销毁!");
        result5.put("type","success");
        System.out.println("成功注销！");

        JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
        System.out.println(result8);

        return result8;
    }


    @GetMapping(value = "/Toindex")
    public ModelAndView Toindex(String name) {
        ModelAndView modelAndView =new ModelAndView();
        modelAndView.addObject("name",name);
        modelAndView.setViewName("index");//跳转到这个jsp页面来渲染表格
        return modelAndView;
    }


    @Autowired
    userService userService;

    @Autowired
    com.example.demo.entity.useracount useracount;

    @Autowired
    com.example.demo.datasource.multi.entity.user user;
    @Autowired
    com.example.demo.datasource.multi.dao.usermapper usermapper;


    @ResponseBody
    @RequestMapping(value = {"/login"})
    public JSONObject login1(@RequestBody useracount params, Model model, HttpServletRequest request, HttpServletResponse response) {
        log.info("进入登录");
        System.out.println(params);
        Userparam user = new Userparam();

        String sql="select * from user where username = '"+params.getUsername()+"'";

        user theuser=usermapper.getuser(sql);
        String username = params.getUsername();
        String password = params.getPassword();
        user.setUsername(username);
        user.setUserpassword(password);

        if (theuser != null) {
            String pwd=theuser.getPassword();

            if(theuser.getStatus().equals("1")){

                Map<String, Object> result5 = new HashMap<String,Object>();
                result5.put("code",-1);
                result5.put("result",null);
                result5.put("message","此账号已被禁用，请联系管理员！");
                result5.put("type","error");

                JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
                System.out.println(result8);

                return result8;
            }

            if (pwd.equals(password)){
                    HttpSession session1 = request.getSession();
                    //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
                    Userparam user1 = (Userparam) session1.getAttribute(session1.getId());

                model.addAttribute(session1.getId(), user);
                request.getSession().setAttribute(session1.getId(), user);
                //获取session
                HttpSession session = ((ServletRequestAttributes) RequestContextHolder
                        .getRequestAttributes()).getRequest().getSession();
                // 在sesssion 中存储用户信息
                session.setAttribute(session.getId(), user);
                //设置session过期时间为60s 默认是1800s，指的是在不进行任何操作的情况下，超时时间，（即若    处于操作时间期间的话，则自动延长超时时间）
                log.info("sessionid:"+session.getId());
                session.setMaxInactiveInterval(28800);
                System.out.println(model.getAttribute(session1.getId()));
                log.info(model.getAttribute(session1.getId()).toString());
                Userparam user3= (Userparam) model.getAttribute(session1.getId());
                log.info("登入用户："+user3.getUsername());


                Map<String, Object> result7 = new HashMap<String,Object>();
                result7.put("roleName",theuser.getRoleName());
                result7.put("value",theuser.getRolevalue());

                Map<String, Object> result6 = new HashMap<String,Object>();
                result6.put("roles",result7);
                result6.put("userId",theuser.getUserId());
                result6.put("username",theuser.getUsername());
                result6.put("token",theuser.getToken());
                result6.put("realName",theuser.getRealName());
                result6.put("desc",theuser.getDesc());

                Map<String, Object> result5 = new HashMap<String,Object>();
                result5.put("code",0);
                result5.put("result",result6);
                result5.put("message","ok");
                result5.put("type","success");

                JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
                System.out.println(result8);

                return result8;


            }else {
                Map<String, Object> result5 = new HashMap<String,Object>();
                result5.put("code",-1);
                result5.put("result",null);
                result5.put("message","密码错误！");
                result5.put("type","error");

                JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
                System.out.println(result8);

                return result8;

            }


        } else {
            Map<String, Object> result5 = new HashMap<String,Object>();
            result5.put("code",-1);
            result5.put("result",null);
            result5.put("message","无此账号，请先注册！");
            result5.put("type","error");

            JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
            System.out.println(result8);

            return result8;
        }


    }




    @Autowired
    com.example.demo.util.getip getip;
    /**
     * 端口
     */
    @Value("${server.port}")
    private String port;

    @ResponseBody
    @GetMapping(value = {"/getUserInfo"})
    public JSONObject getUserInfo(HttpServletRequest request) {

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        log.info("获取用户信息:"+user.getUsername());
        String sql="select * from user where username = '"+user.getUsername()+"'";

        user theuser=usermapper.getuser(sql);
        String username = user.getUsername();
        String password = user.getUserpassword();

        if (theuser != null) {

                Map<String, Object> result7 = new HashMap<String,Object>();
                result7.put("roleName",theuser.getRoleName());
                result7.put("value",theuser.getRolevalue());


                InetAddress ia = null;
                try {
                    ia = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }

                String ip = getip.getip(request);
                //头像url
                String newfilename = "http://" + ip + ":" + port + "/files/"+theuser.getAvatar();
                System.out.println("头像url:"+newfilename);

                Map<String, Object> result6 = new HashMap<String,Object>();
                result6.put("id",theuser.getId());
                result6.put("roles",result7);
                result6.put("userId",theuser.getUserId());
                result6.put("username",theuser.getUsername());
                result6.put("password",theuser.getPassword());
                result6.put("avatar",newfilename);
                result6.put("token",theuser.getToken());
                result6.put("homePath",theuser.getHomePath());
                result6.put("realName",theuser.getRealName());
                result6.put("desc",theuser.getDesc());

                Map<String, Object> result5 = new HashMap<String,Object>();
                result5.put("code",0);
                result5.put("result",result6);
                result5.put("message","ok");
                result5.put("type","success");

                JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
                System.out.println(result8);

                return result8;

        } else {
            Map<String, Object> result5 = new HashMap<String,Object>();
            result5.put("code",-1);
            result5.put("result",null);
            result5.put("message","未获得相应的用户信息!");
            result5.put("type","error");

            JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
            System.out.println(result8);

            return result8;
        }


    }

    @ResponseBody
    @GetMapping(value = {"/getPermCode"})
    public JSONObject getPermCode(HttpServletRequest request, HttpServletResponse response) {

        HttpSession session1 = request.getSession();
        //统一拦截（查询当前session是否存在user）(这里user会在每次登录成功后，写入session)
        Userparam user = (Userparam) session1.getAttribute(session1.getId());
        log.info("获取用户信息:"+user.getUsername());
        String sql="select id from user where username = '"+user.getUsername()+"'";
        String userId  = usermapper.getuserId(sql);

        String sql1="select * from fakecode where userId = "+userId+"";
        List<fakeCode> getfakeCodeList=usermapper.getfakeCodeList(sql1);

        if (getfakeCodeList.size() >0) {
            List<String> fakeCodeList = new ArrayList<>();
            for (fakeCode t:getfakeCodeList
            ) {
                fakeCodeList.add(t.getCode());
            }

                Map<String, Object> result7 = new HashMap<String,Object>();
                result7.put(userId,fakeCodeList);
            System.out.println(result7);

                Map<String, Object> result5 = new HashMap<String,Object>();
                result5.put("code",0);
                result5.put("result",result7);
                result5.put("message","ok");
                result5.put("type","success");

                JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
                System.out.println(result8);

                return result8;

        } else {
            Map<String, Object> result5 = new HashMap<String,Object>();
            result5.put("code",-1);
            result5.put("result",null);
            result5.put("message","令牌无效,未登录!");
            result5.put("type","error");

            JSONObject result8 = JSONObject.parseObject(JSON.toJSONString(result5));
            System.out.println(result8);

            return result8;
        }


    }



}
